require 'sitemap_spider/sitemap'

module SitemapSpider    # our private namespace
  module SitemapBase  # is included to ActiveRecord::Base
    def self.included(klass)
      klass.extend(ClassMethods)
    end

    module ClassMethods
      def updates_sitemap(sitemap_name = Sitemaps::DEFAULT_SITEMAP_NAME)
        after_create Callbacks.new(sitemap_name)
        before_update Callbacks.new(sitemap_name)
        before_destroy Callbacks.new(sitemap_name)
      end
    end

    class Callbacks
      def initialize(sitemap_name)
        @sitemap_name = sitemap_name
      end

      # Add record to a sitemap.
      def after_create(record)
        Sitemaps.do(@sitemap_name, :update_records, [record], nil)
        true
      end

      # Delete the older record (reload from database) and then add the newer.
      def before_update(record)
        Sitemaps.do(@sitemap_name, :update_records, [record], [record.class.find(record)])
        true
      end

      # Delete record from a sitemap.
      def before_destroy(record)
        Sitemaps.do(@sitemap_name, :update_records, nil, [record])
        true
      end
    end
  end

  # Holds configuration for sitemaps, passes the appropriate options
  # for given sitemap to new Sitemap object. 
  class Sitemaps
    DEFAULT_SITEMAP_NAME = :main_sitemap
    @@sitemaps = {}

    # Add (merge) configuration hash for +sitemap_name+ to <tt>@@sitemaps</tt>. The configuration
    # hash (+opts+) gets merged with default Sitemap options.
    def self.config(sitemap_name = DEFAULT_SITEMAP_NAME, opts = {})
      @@sitemaps.merge!({sitemap_name => Sitemap.default_opts.merge(opts)})
    end

    # Pass requests to Sitemap class.
    def self.do(sitemap_name, sm_meth, *args)
      Sitemap.new(@@sitemaps[sitemap_name]).send(sm_meth, *args)
    end
  end
end
